﻿using Abp.Collections.Extensions;
using Abp.Extensions;
using Abp.UI;
using Mt.Site.Core.WorkFlows.Design.Cache;
using Mt.Site.Core.WorkFlows.Enum;
using Mt.Site.Core.WorkFlows.Process;
using Mt.Site.Core.WorkFlows.Process.Entities;
using Mt.Site.Core.WorkFlows.Process.Models;
using Mt.Site.Core.WorkFlows.Process.Stores;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Mt.Site.Core.WorkFlows.Diy
{
    internal static class DiyStaticFunction
    {
        //public const string DayCountField = "Leibieshijian";

        //internal static double GetQjDayCount(string data)
        //{
        //    if (string.IsNullOrEmpty(data))
        //        return 0;

        //    var arr = JArray.Parse(data);
        //    double count = 0;
        //    foreach (var item in arr)
        //    {
        //        var zongshu = item.Value<double>("zongshu");
        //        count += zongshu;
        //    }

        //    return count;
        //}

        //internal static async Task SendToDealWithNodeAsync(
        //    IWorkFlowManager workFlowManager,
        //    string replyMsg,
        //    WorkFlowProcessDto current,
        //    Design.IWorkflowNodeDefinition nextNode,
        //    string yueUserIds,
        //    string bushiyueUserIds,
        //    Action<WorkFlowProcessDto> action = null)
        //{
        //    var allData = await workFlowManager.GetAllProcessDataAsync();
        //    List<WfUserQueueItem> yueUsers, banUsers;
        //    CheckUsers(workFlowManager, allData, yueUserIds, bushiyueUserIds, out yueUsers, out banUsers);

        //    await workFlowManager.GoNext(
        //        current, banUsers, yueUsers, nextNode.Definition.NodeId, ActionScheme.Parallel, replyMsg, action);
        //}


        //internal static async Task SendToDealWithNode2Async(
        //    IWorkFlowManager workFlowManager,
        //    string replyMsg,
        //    WorkFlowProcessDto current,
        //    string yueUserIds,
        //    string bushiyueUserIds,
        //    Action<WorkFlowProcessDto> action = null)
        //{
        //    var allData = await workFlowManager.GetAllProcessDataAsync();
        //    List<WfUserQueueItem> yueUsers, banUsers;
        //    CheckUsers(workFlowManager, allData, yueUserIds, bushiyueUserIds, out yueUsers, out banUsers);

        //    var nodeId = workFlowManager.CurrentNode.Definition.NodeId;

        //    await workFlowManager.HasSolved(replyMsg, WorkFlowProcess.DefaultReplyMsg, MoveMode.Leaf, action);

        //    var scheme = $"({EnumHelper.GetEnumDescription(ActionScheme.Parallel)})";

        //    var fromName = await workFlowManager.UserAndUnitFinder.GetUserNameAsync(workFlowManager.UserId);
        //    var nextNames = await workFlowManager.UserAndUnitFinder.GetUserNameListAsync(banUsers.Select(c => c.UserId).Distinct().ToList());
        //    string nextNameStr;
        //    if (yueUsers.Count > 0)
        //    {
        //        var turnRoundUserName = await workFlowManager.UserAndUnitFinder.GetUserNameListAsync(yueUsers.Select(c => c.UserId).Distinct().ToList());
        //        nextNameStr = $"传阅：{turnRoundUserName.JoinAsString("、")}";
        //        if (nextNames.Count > 0)
        //        {
        //            nextNameStr = $"传阅：{turnRoundUserName.JoinAsString("、")}；办理：{nextNames.JoinAsString("、")}";
        //        }
        //        else
        //        {
        //            nextNameStr = $"传阅：{turnRoundUserName.JoinAsString("、")}";
        //        }
        //    }
        //    else
        //    {
        //        nextNameStr = nextNames.JoinAsString("、");
        //    }

        //    写入记录
        //    await workFlowManager.AddLogAsync("送" + workFlowManager.CurrentNode.Definition.Name + scheme, fromName, nextNameStr, current?.Id);


        //    await workFlowManager.AddNewTaskInTrunkAsync(current, banUsers, yueUsers, nodeId, false, ActionScheme.Parallel);
        //}


        //private static void CheckUsers(
        //    IWorkFlowManager workFlowManager,
        //    List<WorkFlowProcessDto> allData,
        //    string yueUserIds,
        //    string bushiyueUserIds,
        //    out List<WfUserQueueItem> yueUsers,
        //    out List<WfUserQueueItem> banUsers)
        //{
        //    var blacklist = allData.Where(c => c.OperationType == OperationType.PassRound).Select(c => c.UserId);
        //    阅
        //    var yueUserIdsList = (yueUserIds.GetArryFromStrBySplit<long>(WorkFlowConst.SplitChars).Union(bushiyueUserIds.GetArryFromStrBySplit<long>(WorkFlowConst.SplitChars)))
        //        .Where(c => !blacklist.Contains(c))
        //        .Distinct()
        //        .Select(c => workFlowManager.UserAndUnitFinder.GetUserInfo(c))
        //        .Where(c => c != null)
        //        .OrderByDescending(c => c.Order)
        //        .Select(c => c.UserId)
        //        .ToList();

        //    yueUsers = yueUserIdsList
        //        .Select(c => new WfUserQueueItem
        //        {
        //            UserId = c,
        //            OperationType = OperationType.PassRound,
        //            TurnRoundUserEndNode = WorkFlowConst.BjOffice2NodeId
        //        })
        //        .ToList();
        //    var paper = workFlowManager.CurrentPaper.Paper;

        //    主办，会办
        //    var mainOperativeUserIdList = paper.MainOperativeUserId.GetArryFromStrBySplit<long>(WorkFlowConst.SplitChars);
        //    paper.UpdateCoOperativeUser(paper.CoOperativeUserIds);  //有可能之前执行过撤回或稿件回退操作，这里恢复表单数据
        //    var coOperativeUserIdList = paper.CoOperativeUserIds.GetArryFromStrBySplit<long>(WorkFlowConst.SplitChars);

        //    var mainOperativeUser = mainOperativeUserIdList
        //        .Select(c => new WfUserQueueItem
        //        {
        //            UserId = c,
        //            OperationType = OperationType.Processing,
        //            ResponsibilityId = null,
        //            Signal = WorkFlowConst.Constant.ZhuBan
        //        })
        //        .ToList();

        //    会办中不能有主办人员
        //   var coOperativeUser = coOperativeUserIdList.Where(c => !mainOperativeUserIdList.Contains(c))
        //       .Select(c => new WfUserQueueItem
        //       {
        //           UserId = c,
        //           OperationType = OperationType.Processing,
        //           ResponsibilityId = null,
        //           Signal = WorkFlowConst.Constant.HuiBan
        //       })
        //       .ToList();

        //    banUsers = mainOperativeUser.Union(coOperativeUser).ToList();
        //}


        public static bool IsApprovalFlow(WorkflowCustomData wfData)
        {
            if (wfData != null && wfData.IsApprovalFlow)
            {
                return true;
            }

            var wfUniqueName = wfData?.UniqueName;

            return wfUniqueName == WorkFlowConst.WorlFlowUniqueNameConst.TouGaoUniqueName;
        }

        public static async Task TougaoFormDataCheckAsync(IWorkFlowFormDataStore workFlowFormDataStore, Guid paperId)
        {
            var menuDataKey = WorkFlowConst.FieldName.Content2.Menu.ToPascalCase();
            var titleDataKey = WorkFlowConst.FieldName.Content2.Title.ToPascalCase();
            var publishDataKey = WorkFlowConst.FieldName.Content2.PublishTime.ToPascalCase();

            //1. 标题不能为空，2. 栏目不能为空， 发布时间
            var datas = await workFlowFormDataStore.GetSpecialFieldAsync(
                new List<string>
                {
                    menuDataKey,
                    titleDataKey,
                    publishDataKey,
                },
                paperId);

            if (!datas.ContainsKey(menuDataKey) || datas[menuDataKey].IsNullOrEmpty())
            {
                throw new UserFriendlyException("请选择推送的栏目！");
            }
            if (!datas.ContainsKey(titleDataKey) || datas[titleDataKey].IsNullOrEmpty())
            {
                throw new UserFriendlyException("标题不能为空！");
            }
            if (!datas.ContainsKey(menuDataKey) || datas[menuDataKey].IsNullOrEmpty())
            {
                throw new UserFriendlyException("发布时间不能为空！");
            }
        }
    }
}
